import {AnyAction, Reducer} from 'redux';
import {EffectsCommandMap} from 'dva';
import {message} from 'antd';
import {publishArticle, publishFetch} from '../service';
import {routerRedux} from "dva/router";

import {IArticle} from "@/pages/articles/data";

export type Effect = (
  action: AnyAction,
  effects: EffectsCommandMap & { select: <T>(func: (state: {}) => T) => T },
) => void;

export interface ModelType {
  namespace: string;
  state: {
    articleDetail: IArticle,
    categoryList: any[]
  };
  effects: {
    publishArticle: Effect;
    publishFetch: Effect;
  };
  reducers: {
    detail: Reducer<{}>;
  };
}


const defaultArticleDetail = {
  id: 0,
  title: '',
  category_id: 0,
  labels: [],
  content: '',
  thumb: [],
  status: 1
};

const Model: ModelType = {
  namespace: 'articles',

  state: {
    articleDetail: defaultArticleDetail,
    categoryList: []
  },

  effects: {
    * publishArticle({payload}, {call, put}) {
      const response = yield call(publishArticle, payload);
      if (response.status === 'ok') {
        message.success('提交成功!!!');
        yield put(routerRedux.replace('/articles/list'));
      }
    },
    * publishFetch({payload}, {call, put}) {
      const response = yield call(publishFetch, payload);
      yield put({
        type: 'detail',
        payload: response.data
      })

    }
  },
  reducers: {

    detail(state, action) {
      console.log('detail');

      let result = Object.assign({}, state, {categoryList: action.payload.categoryList},{
        articleDetail:defaultArticleDetail
      });

      if (action.payload.article) {
        console.log('有值');
        Object.assign(
          result,
          {articleDetail: action.payload.article}
        );
      }else {
        console.log('没值');
      }
      return result
    },
  }
};

export default Model;
